package mysql

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"my_chat/model"
	"my_chat/setting"
)

var db *gorm.DB

func Init(cfg *setting.MySQLConfig) (err error) {
	dsn := fmt.Sprintf("%s:%s@(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", cfg.User, cfg.Password, cfg.Host, cfg.Port, cfg.DB)
	db, err = gorm.Open("mysql", dsn)
	if err != nil {
		fmt.Println(err)
		fmt.Println("连接数据库错误")
		return err
	}
	//自动检查 Product 结构是否变化，变化则进行迁移
	db.AutoMigrate(&model.Community{}, &model.User{}, &model.Contact{}, &model.Message{})
	db.LogMode(true)
	return nil
}

func Close() (err error) {
	_ = db.Close()
	return
}
